use sea_orm::{ActiveModelBehavior, ActiveValue, DatabaseConnection};
use sky_common::constant;
use sky_pojo::entities::orders;


use crate::mapper;

pub async fn process_timeout_order(db: &DatabaseConnection) {
    let mut date_time = chrono::Utc::now().naive_utc();
    tracing::info!("处理支付超时订单 {}", date_time);

    date_time = date_time + chrono::Duration::minutes(-15);

    let orders = match mapper::order::get_by_status_and_ordertime_lt(
        db,
        constant::order::PENDING_PAYMENT,
        date_time,
    )
    .await
    {
        Ok(orders) => orders,
        Err(e) => {
            tracing::error!("{}", e.to_string());

            Vec::new()
        }
    };

    if !orders.is_empty() && orders.len() > 0 {
        for mut order in orders {
            order.status = constant::order::CANCELLED;
            order.cancel_reason = Some("支付超时，自动取消".to_string());
            order.cancel_time = Some(date_time);
            mapper::order::update(db, order.into()).await;
        }
    }
}

pub async fn process_delivery_order(db: &DatabaseConnection) {
    let mut date_time = chrono::Utc::now().naive_utc();
    tracing::info!("处理派送订单 {}", date_time);

    date_time = date_time + chrono::Duration::minutes(-60);

    let orders = match mapper::order::get_by_status_and_ordertime_lt(
        db,
        constant::order::DELIVERY_IN_PROGRESS,
        date_time,
    )
    .await
    {
        Ok(orders) => orders,
        Err(e) => {
            tracing::error!("{}", e.to_string());

            Vec::new()
        }
    };

    if !orders.is_empty() && orders.len() > 0 {
        for order in orders {
            let mut order_active_model = orders::ActiveModel::new();
            order_active_model.id = ActiveValue::set(order.id);
            order_active_model.status = ActiveValue::set(constant::order::COMPLETED);
            mapper::order::update(db, order_active_model).await;
        }
    }
}
